const app = getApp();

Page({
  data: {
    username: '',
    password: '',
    phone: '',
    wechat: ''
  },

  onUsernameInput(e) {
    this.setData({ username: e.detail.value });
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },

  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },

  onWechatInput(e) {
    this.setData({ wechat: e.detail.value });
  },

  async onRegister() {
    const { username, password, phone, wechat } = this.data;
    
    if (!username || !password) {
      wx.showToast({ title: '请填写用户名和密码', icon: 'none' });
      return;
    }

    if (username.length < 3) {
      wx.showToast({ title: '用户名至少3位', icon: 'none' });
      return;
    }

    if (password.length < 6) {
      wx.showToast({ title: '密码至少6位', icon: 'none' });
      return;
    }

    try {
      const result = await app.request('/users/register', 'POST', {
        username,
        password,
        phone,
        wechat
      });

      app.globalData.token = result.token;
      app.globalData.userInfo = result.user;
      
      wx.setStorageSync('token', result.token);
      wx.setStorageSync('userInfo', result.user);

      wx.showToast({ 
        title: '注册成功', 
        icon: 'success',
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    } catch (error) {
      wx.showToast({ title: error.error || '注册失败', icon: 'none' });
    }
  },

  onBack() {
    wx.navigateBack();
  }
});